﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace System.Xml.Linq
{
   public static class XElementExtension
    {
       public static T XGetAttrValue<T>(this XElement node, string attrName, T defaultValue)
       {
           if (node == null)
           {
               return defaultValue;
           }
           if (string.IsNullOrEmpty(attrName))
           {
               return defaultValue;
           }
           XAttribute attr = node.Attribute(attrName);
           if (attr == null)
           {
               return defaultValue;
           }
           return attr.Value.To<T>(defaultValue);
       }

       public static string InnerXml(this XElement xElement)
       {
           //remove start tag
           string innerXml = xElement.ToString().Trim().Replace(string.Format("<{0}>", xElement.Name), "");
           ////remove end tag
           innerXml = innerXml.Trim().Replace(string.Format("</{0}>", xElement.Name), "");
           return innerXml.Trim();
       }
       public static T GetElementValue<T>(this XElement obj, string elementName, T defaultValue)
       {
           if (string.IsNullOrEmpty(elementName))
           {
               throw new ArgumentNullException("elementName");
           }
           if (obj == null)
           {
               return defaultValue;
           }
           XElement element = obj.Element(elementName);
           if (element == null)
           {
               return defaultValue;
           }
           return element.Value.To<T>(defaultValue);
       }


       public static T GetAttributeValue<T>(this XElement obj, string attributeName, T defaultValue)
       {
           if (string.IsNullOrEmpty(attributeName))
           {
               throw new ArgumentNullException("attributeName");
           }
           if (obj == null)
           {
               return defaultValue;
           }
           XAttribute attribute = obj.Attribute(attributeName);
           if (attribute == null)
           {
               return defaultValue;
           }
           return attribute.Value.To<T>(defaultValue);
       }

 
    }
}
